<template>
	<view class="whole":style="{ height: wholeHeight }">
		<release-header-xhd :title="title"
		@go-back="handleGoBack" 
		@publish="handlePublish" 
		></release-header-xhd>
		
		<view class="selectImgHeader">
			<view class="avatar-scroll-container">
			  <view class="loadMore" @click="processImages">
			  		<image class="iconfont icon-jia" ></image>
			  </view>
			  <view 
			    class="avatar-item" 
			    v-for="(image, index) in images" 
			    :key="index" 
			  >
			    <view class="avatarImg" :style="{ backgroundImage: 'url(' + image + ')' }" ></view>
				<image class="iconfont icon-cuowu  removeImg" @click="removeImage(image)"></image>
			  </view>
			</view>
		</view>
		
		<scroll-view
		   class="indexContent"
		   :scroll-y="true"
		 >
		<view class="textInputContainer">
			<textarea v-model="textInput"
			ref="textarea"
			maxlength="1024"
			placeholder="请输入文字..." 
			class="textInput"
			@input="handleInput"
			></textarea>
		</view>
		
		<view class="characterCount">{{ characterCount }}/1024</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				title:"发布动态",
				images: [],// 用于存储接收到的图片路径
				textInput: "", // 用于存储输入的文字
				characterCount: 0 ,// 当前字符数
				wholeHeight :'100vh',
				keyboardHeight:0,
				token:null,
				uid:null,
			};
		},
		onLoad(){
			this.token=uni.getStorageSync("token")||null
			this.uid=uni.getStorageSync('UID')||null
			if(!this.token||!this.uid){
				uni.navigateBack()
				uni.navigateTo({
				url:"/pages/login/login"
			})
			return;
			}
		},
		mounted() {
			 // 监听键盘高度变化
			uni.onKeyboardHeightChange((res) => {
				  this.keyboardHeight = res.height;
				  this.updateWholeHeight();
			});
		},
		methods: {
			removeImage(image) {
			  this.images = this.images.filter((img) => img !== image);
			},
					
			// 处理返回操作
			handleGoBack() {
			  console.log('返回操作');
			  uni.navigateBack();
			},
					
			// 更新字符数
			handleInput(event) {
			  this.characterCount = this.textInput.length;
			},
					
			// 更新页面高度以适配键盘弹起
			updateWholeHeight() {
			  this.wholeHeight = `calc(100vh - ${this.keyboardHeight}px)`;
			},
					
			// 重置表单
			resetForm() {
			  this.textInput = '';
			  this.images = [];
			  this.characterCount = 0;
			},
		  // 上传文字和图片的方法
		  async handlePublish() {
		      if (!this.textInput) {
		          uni.showToast({
		              title: '内容不能为空',
		              icon: 'none',
		          });
		          return;
		      }
		      if (this.images.length === 0) {
		          uni.showToast({
		              title: '至少发一张图片哦',
		              icon: 'none',
		          });
		          return;
		      }
			uni.showLoading({
				title:"发布中……"
			})
		      const timestamp = this.formatDate(new Date());
		  
		      // 确保每张图片的字段名为 imgFiles
		      const imgFiles = this.images;
		      console.log("文件数量", imgFiles.length);
		  
		      // 发起文件上传
		      // 先发布文字，获取帖子id，然后遍历，发送帖子图片
		      let postId = -1;
		  
		      try {
		          const publishResponse = await uni.request({
		              url: this.baseUrl + "/live/publish",
		              method: "POST",
		              header: {
		                  token: this.token, // 身份验证
		                  uid: this.uid,
		              },
		              data: {
		                  data: {
		                      uid: this.uid,
		                      createdAt: timestamp,
		                      text: this.textInput,
		                  },
		                  msgType: "publishLive",
		              },
		          });
		  
		          if (publishResponse.data.code == 1) {
		              postId = publishResponse.data.data;
		  
		              for (let index = 0; index < imgFiles.length; index++) {
		                  const imagePath = imgFiles[index];
		                  const uploadResponse = await uni.uploadFile({
		                      url: this.baseUrl + '/img/uploadLivePhoto', // 替换为你的接口地址
		                      filePath: imagePath,
		                      name: 'livePhoto', // 后端接收文件的字段名
		                      formData: {
		                          postId: Number(postId),
		                          index: index,
		                      },
		                      header: {
		                          'token': this.token,
		                          'uid': this.uid,
		                      },
		                  });
		  
		                  const responseData = JSON.parse(uploadResponse.data);
		                  console.log(responseData.code);
		                  if (responseData.code == 1) {
		                      console.log("上传第" + (index + 1) + "张图片成功！");
		                  } else {
		                      console.error("上传第" + (index + 1) + "张图片失败！");
		                  }
		              }
					uni.hideLoading()
		              uni.showToast({
		                  title: "发布成功！",
		                  icon: "success",
		                  duration: 1000,
		              });
					  setTimeout(()=>{
						  this.resetForm();
						  this.handleGoBack();
					  },500)
		          } else {
					  uni.hideLoading();
		              uni.showToast({
		                  title: "发布失败！",
		                  icon: "error",
		                  duration: 1500,
		              });
		          }
		      } catch (error) {
		          console.error('请求失败', error);
				  uni.hideLoading()
		          uni.showToast({
		              title: "请求失败！",
		              icon: "error",
		              duration: 1500,
		          });
		      }
		  },
		formatDate(date) {
		  const year = date.getFullYear();
		  const month = String(date.getMonth() + 1).padStart(2, '0');
		  const day = String(date.getDate()).padStart(2, '0');
		  const hours = String(date.getHours()).padStart(2, '0');
		  const minutes = String(date.getMinutes()).padStart(2, '0');
		  const seconds = String(date.getSeconds()).padStart(2, '0');
		  
		  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
		},
		
		  // 处理图片选择
		  processImages() {
		    if (this.images.length >= 9) {
		      uni.showToast({
		        title: '最多只能选择9张图片',
		        icon: 'none',
		      });
		    } else {
		      uni.chooseImage({
		        count: 9 - this.images.length, // 默认9张，根据需求调整
		        sizeType: [ 'compressed'], // 原图或压缩图
		        sourceType: ['album'], // 从相册选择
		        success: (chooseImageRes) => {
		          const tempFilePaths = chooseImageRes.tempFilePaths;
		          tempFilePaths.forEach((tempFilePath) => {
		            if (!this.images.includes(tempFilePath)) {
		              this.images.push(tempFilePath);
		            }
		          });
		        },
		        fail: (err) => {
		          console.error('选择图片失败:', err);
		        },
		      });
		    }
		  },
		  // 移除已选图片

		},

	}
</script>

<style lang="scss">
.whole {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f7f9fc; /* 更柔和的背景色 */
  overflow: hidden;

  .indexContent {
    display: flex;
    flex: 1;
    overflow-y: auto;
    background-color: #ffffff;
    position: relative;
    border-radius: 10rpx; /* 圆角 */
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1); /* 更明显的阴影 */

    .textInput {
      background-color: #ffffff; /* 背景色 */
      width: 100%;
	  height:700rpx;
      border: 1px solid #ddd; /* 边框颜色 */
      border-radius: 5rpx; /* 圆角 */
      padding: 10rpx;
      resize: none;
      overflow: hidden;
      font-size: 28rpx; /* 更大的字体 */
      color: #333; /* 字体颜色 */
      box-shadow: inset 0 1rpx 3rpx rgba(0, 0, 0, 0.1); /* 内部阴影 */
    }

    .characterCount {
      position: absolute;
      bottom: 30rpx;
      right: 20rpx;
      color: #999; /* 更柔和的字符计数颜色 */
      font-size: 24rpx; /* 字体大小 */
    }
  }
}

.selectImgHeader {
  display: flex;
  align-items: center;
  overflow-x: auto;
  white-space: nowrap;
  height: 140rpx;
  margin-top: 3rpx;
  background-color: #ffffff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1); /* 阴影效果 */
  border-radius: 10rpx; /* 圆角 */

  .avatar-scroll-container {
    display: inline-flex;
    height: 120rpx;
    margin-right: 20rpx;
    align-items: center;

    .avatar-item {
      padding-top: 3rpx;
      width: 130rpx;
      height: 100%;
      margin-left: 20rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      position: relative;
      border: 2rpx solid #e0e0e0; /* 更柔和的边框 */
      border-radius: 10rpx;
      box-shadow: 0 2rpx 5rpx rgba(0, 0, 0, 0.1);
      transition: all 0.3s; /* 过渡效果 */

      &:hover {
        transform: scale(1.05); /* 鼠标悬停时放大 */
        border-color: #007bff; /* 鼠标悬停时边框颜色变化 */
      }
    }

    .avatarImg {
      width: 95%;
      height: 100rpx;
      background-repeat: no-repeat;
      background-size: cover;
      background-position: center;
      border-radius: 10rpx; /* 圆角 */
    }

    .removeImg {
      z-index: 1;
      top: 5rpx;
      right: 5rpx;
      position: absolute;
      text-align: center;
      font-size: 25rpx;
      height: 25rpx;
      width: 25rpx;
      line-height: 25rpx;
      color: #ff4d4f; /* 删除图标颜色 */
    }

    .loadMore {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: 20rpx;
      width: 100rpx;
      height: 100rpx;
      border: 2rpx dashed #007bff; /* 更醒目的虚线边框 */
      border-radius: 50%;
      background-color: #ffffff;
      box-shadow: 0 2rpx 5rpx rgba(0, 0, 0, 0.1);
      transition: background-color 0.3s;

    }

    .iconfont {
      text-align: center;
      font-size: 50rpx;
      line-height: 100rpx;
      width: 100rpx;
      height: 100rpx;
      color: #007bff; /* 图标颜色 */
    }
  }
}
</style>